<template>
    <a-upload v-if="props.uploadMode === 'defaults'" v-model:file-list="fileList" name="file" :action="action"
        :headers="headers" list-type="picture-card" :maxCount="props.uploadNumber" @change="handleChange"   @preview="handlePreview">
        <div v-if="fileList.length < props.uploadNumber">
            <plus-outlined />
            <div class="ant-upload-text">上传</div>
        </div>
    </a-upload>

    <!-- <a-upload-dragger v-if="props.uploadMode === 'drag'" v-model:fileList="fileList" name="file" :multiple="true"
        :action="action" :headers="headers" :maxCount="props.uploadNumber" @change="handleChange">
        <p class="ant-upload-drag-icon">
            <inbox-outlined />
        </p>
        <p class="ant-upload-text">单击或拖动文件到此区域上传</p>
        <p class="ant-upload-hint"></p>
    </a-upload-dragger> -->

    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
        <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
</template>

<script setup name="uploadIndex">
import tool from '@/utils/tool'
import sysConfig from '@/config/index'

const fileList = ref([])
const emit = defineEmits({ uploadDone: null })
const headers = ref({
    token: tool.data.get('TOKEN')
})

const previewVisible = ref(false);
const previewImage = ref('');

const props = defineProps({
    action: {
        type: String,
        default: '/dev/file/uploadDynamicReturnUrl',
        required: false
    },
    // 上传方式 defaults || drag
    uploadMode: {
        type: String,
        default: 'defaults',
        required: false
    },
    // 上传数量
    uploadNumber: {
        type: Number,
        default: 1,
        required: false
    },
    modelValue: {
    type: [String, Object, Array],
    default: () => []
  },
})

watch(
  () => props.modelValue,
  async (val) => {
    if (val) {
      // 首先将值转为数组
      let list= [];
      if (Array.isArray(val)) {
        list = val ;
      } else{
        list=[val]
      }
      // 然后将数组转为对象数组
      fileList.value = list.map((item) => {
        // 字符串回显处理 如果此处存的是url可直接回显 如果存的是id需要调用接口查出来
        let itemData;
        if (typeof item === 'string') {
          itemData = { name: item, url: item };
        } 
        return itemData;
      });
    } else {
      fileList.value = [];
      return [];
    }
  },
  { deep: true, immediate: true }
);
const action = sysConfig.API_URL + props.action

// 上传时间，构造上传数组，主动推送至调用组件，单文件可以使用
const handleChange = ({file,list,event}) => {
    // 单个文件可以使用回调方法，多个文件建议主动获取
    let result = []
    for (let a = 0; a < props.uploadNumber; a++) {
        // const file = fileList.value[a]
        if (file && file.status === 'done'  && file.response) {
            console.log(file)
            const resultObj = {
                name: file.name,
                url:file.response.data
            }
            result.push(resultObj)

             emit('update:modelValue', listToString(result));
        }
        if (file && file.status === 'removed' ) {

            emit('update:modelValue', listToString(fileList.value));
        }
    }

    if (result.length > 0) {
        emit('uploadDone', result)
    }
}
// 通过DOM获取上传的文件
const uploadFileList = () => {
    if (fileList.value) {
        const result = []
        // 只返回这些就够用了，其他基本用不到
        fileList.value.forEach((item) => {
            const obj = {
                name: item.name,
                type: item.type,
                size: item.size,
                url: item.url
            }
            result.push(obj)
        })
        return result
    } else {
        return []
    }
}

// 对象转成指定字符串分隔
const listToString = (list) => {
  let strs = '';
  let separator = ',';
  for (let i in list) {
      strs += list[i].url +separator;
  }
  return strs != '' ? strs.substring(0, strs.length - 1) : '';
};

const handleCancel = () => {
      previewVisible.value = false;
    };
    const handlePreview = async (file) => {
   
      previewImage.value = file.url || file.preview;
      previewVisible.value = true;
    };
// 抛出这个获取文件列表的方法
defineExpose({
    uploadFileList
})
</script>
